package com.learning.optimize.jdk.annotation.sql;

import com.google.common.base.Joiner;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: TableCreator
 * Description: 表创建
 * Date: 2018/7/18 15:06 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class TableCreator {

    public static String createTableSql(String className) throws ClassNotFoundException {
        Class<?> cl = Class.forName(className);
        Table dbTable = cl.getAnnotation(Table.class);
        //如果没有表注解，直接返回
        if (dbTable == null) {
            System.out.println("No DBTable annotations in class " + className);
            return null;
        }
        String tableName = dbTable.name();
        // If the name is empty, use the Class name:
        if (tableName.length() < 1) {
            tableName = cl.getName().toUpperCase();
        }
        List<String> columnDefs = new ArrayList<String>();
        //通过Class类API获取到所有成员字段
        for (Field field : cl.getDeclaredFields()) {
            String columnName;
            String columnType;
            //获取字段上的注解
            Annotation[] anns = field.getDeclaredAnnotations();
            if (anns.length < 1) {
                continue; // Not a db table column
            }

            // 这边简单处理
            Class<?> type = field.getType();
            if (type == int.class || type == Integer.class) {
                columnType = " INT(%s)";
            } else {
                columnType = " VARCHAR(%s)";
            }

            for (Annotation ann : anns) {
                if (ann instanceof Column) {
                    Column column = (Column) ann;

                    if (column.name().length() < 1) {
                        columnName = field.getName().toUpperCase();
                    } else {
                        columnName = column.name();
                    }
                    //构建语句
                    columnDefs.add(columnName + String.format(columnType, column.value()) + getConstraints(column.constraint()));
                }
            }
        }


        //数据库表构建语句
        String columns = Joiner.on(",\n    ").join(columnDefs);
        return "CREATE TABLE " + tableName + "(\n    " + columns + "\n);";
    }


    /**
     * 判断该字段是否有其他约束
     *
     * @param con
     * @return
     */
    private static String getConstraints(Constraints con) {
        String constraints = "";
        if (!con.allowNull()) {
            constraints += " NOT NULL";
        }
        if (con.primaryKey()) {
            constraints += " PRIMARY KEY";
        }
        if (con.unique()) {
            constraints += " UNIQUE";
        }
        return constraints;
    }

    public static void main(String[] args) throws Exception {

        String className = "com.learning.optimize.jdk.annotation.sql.Person";
        System.out.println(createTableSql(className));


        /*
        输出：
         CREATE TABLE sys_person(
            ID VARCHAR(50) NOT NULL PRIMARY KEY,
            NAME VARCHAR(30) NOT NULL,
            AGE INT(16) NOT NULL,
            DESCRIPTION VARCHAR(150)
         );
        */
    }
}